package com.bianguo.android.functiondemo.view.activity;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.bianguo.android.functiondemo.R;
import com.bianguo.android.functiondemo.adapter.SuspensionAdapter;
import com.bianguo.android.functiondemo.utils.MLog;

import java.util.ArrayList;

import butterknife.BindView;

public class SuspensionActivity extends BaseActivity {

    @BindView(R.id.suspension_title)
    TextView suspensionTv;
    @BindView(R.id.suspension_recycler)
    RecyclerView mRecycler;

    private SuspensionAdapter adapter;
    private LinearLayoutManager layoutManager;
    private int mCurrentPosition;
    private int suspensionHeight;

    @Override
    public int layoutId() {
        return R.layout.activity_suspension;
    }

    @Override
    public void initView(@Nullable Bundle savedInstanceState) {
        layoutManager = new LinearLayoutManager(this);
        mRecycler.setLayoutManager(layoutManager);
        ArrayList<String> list = new ArrayList<>();
        for (int i = 0; i < 30; i++) {
            list.add("item ---> " + i);
        }
        adapter = new SuspensionAdapter(this, list);
        mRecycler.setAdapter(adapter);
        suspensionTv.setText(list.get(0));
        mRecycler.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                suspensionHeight = suspensionTv.getHeight();
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                View view = layoutManager.findViewByPosition(mCurrentPosition + 1);
                int top = view.getTop();
                if (top <= suspensionHeight) {
                    suspensionTv.setY(-(suspensionHeight - top));
                } else {
                    suspensionTv.setY(0);
                }
                int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();
                if (mCurrentPosition != firstVisibleItemPosition) {
                    mCurrentPosition = firstVisibleItemPosition;
                    suspensionTv.setText(adapter.getList().get(mCurrentPosition));
                }
            }
        });
    }
}
